<template>
   <div class="app-container ">
			<el-splitter :layout="appStore.device === 'mobile'? 'vertical': 'horizontal'" class="default-theme full-hihght">
        <el-splitter-panel size="320" min="294">
					<div class="left-box default-padding">
						<div class="left-head">
							<el-input v-model="dictName" placeholder="请输入字典名称" clearable prefix-icon="Search" style="margin-bottom: 16px" />
							<el-row :gutter="10" style="margin-bottom: 16px">
								<el-col :span="1.5">
									<el-button type="primary"	icon="Plus" @click="handleAdd" v-hasPermi="['system:menu:add']">新增</el-button>
								</el-col>
								<el-col :span="1.5">
									<el-button type="primary"	icon="Edit" :disabled="!curDict" @click="handleUpdate" v-hasPermi="['system:dict:edit']">编辑</el-button>
								</el-col>
								<el-col :span="1.5">
									<el-button type="danger" icon="Delete" :disabled="!curDict" @click="handleDelete" v-hasPermi="['system:dict:remove']">删除</el-button>
								</el-col>
							</el-row>
						</div>
						<div class="left-container" v-loading="dictLoading" element-loading-text="正在加载字典，请稍候">
							<div :class="['dict-item', curDict && curDict.dictId === item.dictId? 'active' : '']" v-for="item in dictOptions" @click="selectDict(item)">
								<span class="dict-name">{{ item.dictName }}</span>
								<span class="dict-type">{{ item.dictType }}</span>
							</div>
						</div>
					</div>
        </el-splitter-panel>
        <el-splitter-panel>
          <div class="right-box default-padding" v-if="curDict">
						<div class="title">基本信息</div>
						<el-row :gutter="20" class="info">
							<el-col :sm="12" :lg="8">字典名称：{{ curDict.dictName }}</el-col>
							<el-col :sm="12" :lg="8">字典类型：{{ curDict.dictType }}</el-col>
							<el-col :sm="12" :lg="8">备注：{{ curDict.remark || '--' }}</el-col>
						</el-row>
						<div class="title mrg-top">字典项列表</div>
						<div class="query-box">
							<el-form :model="queryParams" ref="queryRef" :inline="true" label-width="auto">
								<el-form-item label="标签" prop="label">
									<el-input v-model="queryParams.label" placeholder="请输入标签" clearable style="width: 200px" @keyup.enter="handleQuery" />
								</el-form-item>
								<el-form-item label="值" prop="value">
									<el-input	v-model="queryParams.value" placeholder="请输入值" clearable style="width: 200px" @keyup.enter="handleQuery" />
								</el-form-item>
								<el-form-item>
									<el-button type="primary" @click="handleQuery">搜索</el-button>
									<el-button @click="resetQuery">重置</el-button>
								</el-form-item>
							</el-form>
							<el-button type="primary"	icon="Plus" @click="handleItemAdd" v-hasPermi="['system:menu:add']">新增</el-button>
						</div>
						<el-table border v-loading="loading" element-loading-text="正在加载字典项，请稍候" :data="dataList">
							<el-table-column label="序号" type="index" width="60">
          			<template #default="scope">{{ (queryParams.current - 1) * queryParams.size + scope.$index + 1}}</template>
        			</el-table-column>
							<el-table-column label="标签" prop="label">
									<template #default="scope">
										<span v-if="(scope.row.listClass == '' || scope.row.listClass == 'default') && (scope.row.cssClass == '' || scope.row.cssClass == null)">{{ scope.row.label }}</span>
										<el-tag v-else :type="scope.row.listClass" :class="scope.row.cssClass">{{ scope.row.label }}</el-tag>
									</template>
							</el-table-column>
							<el-table-column label="值" prop="value" />
							<el-table-column label="排序" prop="sort" align="center" width="80" />
							<el-table-column label="创建时间" prop="createTime" align="center" width="180">
									<template #default="scope">
										<span>{{ parseTime(scope.row.createTime) }}</span>
									</template>
							</el-table-column>
							<el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
									<template #default="scope">
										<el-button link type="primary" icon="Edit" @click="handleItemUpdate(scope.row)" v-hasPermi="['system:dict:edit']">编辑</el-button>
										<el-button link type="danger" icon="Delete" @click="handleItemDelete(scope.row)" v-hasPermi="['system:dict:remove']">删除</el-button>
									</template>
							</el-table-column>
						</el-table>

						<pagination v-show="total > 0" :total="total" v-model:page="queryParams.current" v-model:limit="queryParams.size" @pagination="getItemList"/>
					</div>
					<el-empty description="请在左侧选择字典" v-else />
        </el-splitter-panel>
      </el-splitter>

      <!-- 添加或修改字典对话框 -->
      <el-dialog :title="title" v-model="open" width="500px" append-to-body align-center>
				<el-form ref="dictRef" :model="form" :rules="rules" label-width="auto">
					<el-form-item label="字典名称" prop="dictName">
						<el-input v-model="form.dictName" placeholder="请输入字典名称" />
					</el-form-item>
					<el-form-item label="字典类型" prop="dictType">
						<el-input v-model="form.dictType" placeholder="请输入字典类型" />
					</el-form-item>
					<el-form-item label="备注" prop="remark">
						<el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :rows="3" maxlength="300" show-word-limit></el-input>
					</el-form-item>
				</el-form>
				<template #footer>
					<div class="dialog-footer">
						<el-button type="primary" @click="submitForm">确 定</el-button>
						<el-button @click="cancel">取 消</el-button>
					</div>
				</template>
      </el-dialog>
			<!-- 添加或修改字典项对话框 -->
			<el-dialog :title="titleItem" v-model="openItem" width="500px" append-to-body>
         <el-form ref="dataRef" :model="formItem" :rules="rulesItem" label-width="auto">
            <el-form-item label="数据标签" prop="label">
              <el-input v-model="formItem.label" placeholder="请输入数据标签" />
            </el-form-item>
            <el-form-item label="数据键值" prop="value">
              <el-input v-model="formItem.value" placeholder="请输入数据键值" />
            </el-form-item>
						<el-form-item label="排序" prop="sort">
              <el-input-number v-model="formItem.sort" controls-position="right" :min="0" />
            </el-form-item>
            <el-form-item label="样式属性" prop="cssClass">
              <el-input v-model="formItem.cssClass" placeholder="请输入样式属性" />
            </el-form-item>
            <el-form-item label="回显样式" prop="listClass">
							<el-select v-model="formItem.listClass">
								<el-option v-for="item in listClassOptions" :key="item.value" :label="item.label + '(' + item.value + ')'" :value="item.value"></el-option>
							</el-select>
            </el-form-item>
         </el-form>
         <template #footer>
            <div class="dialog-footer">
               <el-button type="primary" @click="submitItemForm">确 定</el-button>
               <el-button @click="cancelItem">取 消</el-button>
            </div>
         </template>
      </el-dialog>
   </div>
</template>

<script setup name="Dict">
import useAppStore from '@/store/modules/app'
import useDictStore from '@/store/modules/dict'
import { debounce } from "@/utils/index"
import { listType, getType, delType, addType, updateType } from "@/api/system/dict/type"
import { listData, getData, delData, addData, updateData } from "@/api/system/dict/data"

const appStore = useAppStore()
const { proxy } = getCurrentInstance()

const dictLoading = ref(true)
const dictName = ref("")
const dictOptions = ref([])
const dictAll = ref([])
const curDict = ref(null)
const open = ref(false)
const title = ref("")

const data = reactive({
  form: {},
  rules: {
    dictName: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
    dictType: [{ required: true, message: "字典类型不能为空", trigger: "blur" }]
  },
})
const { form, rules } = toRefs(data)

const loading = ref(true)
const total = ref(0)
const dataList = ref([])
const titleItem = ref("")
const openItem = ref(false)
const dataItem = reactive({
  formItem: {},
  queryParams: {
    current: 1,
    size: 10,
    label: undefined,
    value: undefined,
    dictId: undefined
  },
  rulesItem: {
    label: [{ required: true, message: "数据标签不能为空", trigger: "blur" }],
    value: [{ required: true, message: "数据键值不能为空", trigger: "blur" }],
    sort: [{ required: true, message: "排序不能为空", trigger: "blur" }]
  }
})
const { queryParams, formItem, rulesItem } = toRefs(dataItem)
const listClassOptions = ref([
  { value: "default", label: "默认" }, 
  { value: "primary", label: "主要" }, 
  { value: "success", label: "成功" },
  { value: "info", label: "信息" },
  { value: "warning", label: "警告" },
  { value: "danger", label: "危险" }
])

function getDictList() {
	dictLoading.value = true
  listType({size: -1}).then(response => {
		const result = response.result || {}
		dictAll.value = result.records || []
    dictOptions.value = result.records || []
		dictLoading.value = false
  })
}

watch(dictName, val => {
	debounce(() => {
		dictOptions.value = dictAll.value.filter(item => item.dictName.includes(val))
  }, 500)()
})

function selectDict(item) {
	curDict.value = item
	queryParams.value.dictId = item.dictId
	getItemList()
}

/** 查询字典类型列表 */
function getItemList() {
  loading.value = true
  listData(queryParams.value).then(response => {
		const result = response.result || {}
    dataList.value = result.records || []
    total.value = Number(result.total)
    loading.value = false
  })
}

/** 表单重置 */
function reset() {
  form.value = {
    dictId: undefined,
    dictName: undefined,
    dictType: undefined,
    remark: undefined
  }
  proxy.resetForm("dictRef")
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = "新增字典"
}

/** 修改按钮操作 */
function handleUpdate() {
  reset()
  const dictId = curDict.value.dictId
  getType(dictId).then(response => {
    form.value = response.result || {}
    open.value = true
    title.value = "编辑字典"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["dictRef"].validate(valid => {
    if (valid) {
      if (form.value.dictId != undefined) {
        updateType(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getDictList()
					getItemList()
        })
      } else {
        addType(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getDictList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete() {
  const dictIds = curDict.value.dictId
	const dictName = curDict.value.dictName
  proxy.$modal.confirm('是否确认删除字典名称为"' + dictName + '"的字典？').then(function() {
    return delType(dictIds)
  }).then(() => {
    getDictList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}


function handleQuery() {
  queryParams.value.current = 1
  getItemList()
}

function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

function resetItem() {
  formItem.value = {
    itemId: undefined,
		dictId: undefined,
		dictType: undefined,
    label: undefined,
    value: undefined,
    cssClass: undefined,
    listClass: "default",
    sort: 0,
  }
  proxy.resetForm("dataRef")
}

function cancelItem() {
  openItem.value = false
  resetItem()
}

function handleItemAdd() {
  resetItem()
	formItem.value.dictId = curDict.value.dictId
	formItem.value.dictType = curDict.value.dictType
  openItem.value = true
  titleItem.value = "添加字典项"
}

function handleItemUpdate(row) {
  resetItem()
  const itemId = row.itemId
  getData(itemId).then(response => {
    formItem.value = response.result || {}
    openItem.value = true
    titleItem.value = "编辑字典项"
  })
}

function submitItemForm() {
  proxy.$refs["dataRef"].validate(valid => {
    if (valid) {
      if (formItem.value.itemId != undefined) {
        updateData(formItem.value).then(response => {
					useDictStore().removeDict(curDict.value.dictType)
          proxy.$modal.msgSuccess("修改成功")
          openItem.value = false
          getItemList()
        })
      } else {
        addData(formItem.value).then(response => {
					useDictStore().removeDict(curDict.value.dictType)
          proxy.$modal.msgSuccess("新增成功")
          openItem.value = false
          getItemList()
        })
      }
    }
  })
}

function handleItemDelete(row) {
  const itemIds = row.itemId
	const itemName = row.label
  proxy.$modal.confirm('是否确认删除字典项名称为"' + itemName + '"的字典项？').then(function() {
    return delData(itemIds)
  }).then(() => {
    getItemList()
    proxy.$modal.msgSuccess("删除成功")
		useDictStore().removeDict(queryParams.value.dictType)
  }).catch(() => {})
}

getDictList()
</script>

<style lang="scss" scoped>
.app-container {
	padding: 0;
	font-size: var(--el-font-size-base);
	.left-box{
		height: 100%;
		display: flex;
		flex-direction: column;
		:deep(.el-input__wrapper) {
			border-radius: 18px;
		}
		.left-head{
			flex-shrink: 1;
		}
		.left-container{
			flex: 1;
			overflow-y: auto;
			.dict-item{
				padding: 12px 16px;
				border-radius: 4px;
				display: flex;
				align-items: center;
				gap: 12px;
				cursor: pointer;
				&:hover{
					background-color: var(--el-color-primary-light-9);
				}
				&.active{
					background-color: var(--el-color-primary-light-5);
				}
				.dict-name{
					font-weight: 600;
				}
				.dict-type{
					color: var(--el-text-color-secondary);
				}
			}
		}
	}
	.right-box{
		height: 100%;
		overflow-y: auto;
	}
	.title{
		margin-bottom: 16px;
		padding-left: 8px;
		font-weight: 600;
		font-size: var(--el-font-size-medium);
		position: relative;
		&::before{
			content: '';
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-40%);
			width: 4px;
			height: 60%;
			background-color: var(--el-color-primary);
		}
	}
	.info{
		padding: 7px 0;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}
	.query-box{
		display: flex;
		justify-content: space-between;
	}
	.mrg-top{
		margin-top: 16px;
	}
	.default-padding{
		padding: 16px;
	}
}
</style>